use strict;
use DBI;
require XML::Twig;


# Return a connection with the bugzilla database.
my $self = {};
my $dbname = "bugs";
my $dbuname = "bugs";
my $bug_db_password = "sockmonkey";
my $bug_db_host = "localhost";
my $bug_db_user_id = 9;
my $pri_thresh = 4;

my $numArgs = $#ARGV + 1;

if( $numArgs < 1) {
        die "Not enough arguments supplied";
}

my $filepath = $ARGV[0];
my $xTwig = XML::Twig->new();
my $xDoc = $xTwig->safe_parsefile($filepath);
my $xRoot = $xDoc->root( );
unless( $xRoot ) {
    die "Error : XML in $filepath could not be parsed : $!";
}

my $pri = $xRoot->first_child('priority')->text();
my $sev = $xRoot->first_child('severity')->text();
my $bugid = $xRoot->first_child('defect_id')->text();


if( $pri >= $pri_thresh ) {
        my $comment = "New Code Review Comment Added \n";
        $comment .= $xRoot->first_child('review_url')->text() . "\n";
        $comment .= "Author: " . $xRoot->first_child('user')->text() . "\n";
        $comment .= "Severity: " . $sev . "\n";
        $comment .= "Priority: " . $pri . "\n\n";
        $comment .= "Comment:" . "\n";
        $comment .= $xRoot->first_child('comment_text')->text();
        #print $comment;
        
        # Create the necessary prepared statements.
        my $dbh = DBI->connect("DBI:mysql:dbname=$dbname;host=$bug_db_host",
                     $dbuname, $bug_db_password,
                     { RaiseError => 1, AutoCommit => 1 });
        
        $self->{dbh} = $dbh;
        
        my $insert_comment =
        $self->{dbh}->prepare_cached('INSERT INTO longdescs ' .
                                     '(bug_id, who, bug_when, thetext) ' .
                                     'VALUES (?, ?, now(), ?)');
        my $update_bug =
        $self->{dbh}->prepare_cached('UPDATE bugs SET delta_ts = now() ' .
                                     'WHERE bug_id = ?');
        
        # Execute the statements.
        $insert_comment->execute($bugid, $bug_db_user_id, $comment);
        $update_bug->execute($bugid);
}

